import 'dart:collection';
import 'dart:io';

import 'package:base/utils/text_util.dart';
import 'package:base/widgets/error_view.dart';
import 'package:base/widgets/square_progress_indicator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

//webview封装
class WebView extends StatefulWidget {
  final String url;

  final PullToRefreshOptions? options;

  WebView({required this.url, this.options, Key? key}) : super(key: key);

  @override
  _WebViewState createState() => new _WebViewState();
}

class _WebViewState extends State<WebView> {
  late InAppWebViewController _webViewController;
  InAppWebViewGroupOptions _options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  late PullToRefreshController _pullToRefreshController;
  double _progress = 0;

  bool _isRefresh = false;

  String? _error;

  @override
  void initState() {
    super.initState();
    _pullToRefreshController = PullToRefreshController(
      options: widget.options ?? PullToRefreshOptions(color: Colors.blue),
      onRefresh: () async {
        _isRefresh = true;
        _error = null;
        if (Platform.isAndroid) {
          _webViewController.reload();
        } else if (Platform.isIOS) {
          _webViewController.loadUrl(
              urlRequest: URLRequest(url: await _webViewController.getUrl()));
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    int index = 0;
    if (_isRefresh) {
      index = 0;
    } else {
      if (TextUtil.isEmpty(_error)) {
        index = _progress > 0.6 ? 0 : 1;
      } else {
        index = 2;
      }
    }
    return WillPopScope(
      onWillPop: () async {
        bool canBack = await _webViewController.canGoBack();
        if (canBack) {
          _webViewController.goBack();
          return Future.value(false);
        } else {
          return Future.value(true);
        }
      },
      child: Material(
        color: Colors.white,
        child: Stack(
          children: [
            IndexedStack(
              index: index,
              children: [
                InAppWebView(
                  initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
                  initialUserScripts: UnmodifiableListView<UserScript>([]),
                  initialOptions: _options,
                  pullToRefreshController: _pullToRefreshController,
                  onWebViewCreated: (controller) {
                    _webViewController = controller;
                  },
                  onLoadStart: (controller, url) {},
                  androidOnPermissionRequest:
                      (controller, origin, resources) async {
                    return PermissionRequestResponse(
                        resources: resources,
                        action: PermissionRequestResponseAction.GRANT);
                  },
                  shouldOverrideUrlLoading:
                      (controller, navigationAction) async {
                    var uri = navigationAction.request.url;

                    if (![
                      "http",
                      "https",
                      "file",
                      "chrome",
                      "data",
                      "javascript",
                      "about"
                    ].contains(uri!.scheme)) {
                      return NavigationActionPolicy.CANCEL;
                    }

                    return NavigationActionPolicy.ALLOW;
                  },
                  onLoadStop: (controller, url) async {
                    _pullToRefreshController.endRefreshing();
                    _isRefresh = false;
                  },
                  onLoadError: (controller, url, code, message) {
                    _pullToRefreshController.endRefreshing();
                    _isRefresh = false;
                    _error = message;
                  },
                  onProgressChanged: (controller, progress) {
                    if (progress == 100) {
                      _pullToRefreshController.endRefreshing();
                      _isRefresh = false;
                    }
                    setState(() {
                      this._progress = progress / 100;
                    });
                  },
                  onUpdateVisitedHistory: (controller, url, androidIsReload) {},
                  onConsoleMessage: (controller, consoleMessage) {
                    print(consoleMessage);
                  },
                ),
                Container(
                  child: Center(
                    child: SquareProgressIndicator(
                      size: 30,
                      color: Theme.of(context).primaryColor,
                    ),
                  ),
                ),
                ErrorView(
                  error: _error,
                )
              ],
            ),
            _progress < 1.0
                ? SizedBox(
                    height: 1.5,
                    child: LinearProgressIndicator(
                      value: _progress,
                    ),
                  )
                : Container(),
          ],
        ),
      ),
    );
  }
}
